package org.example.Java基础.多线程与锁;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class Unsafe类 {

    static class Person {
        private int age = 18;
        private String name = "Tom";

        public Person() {
            System.out.println("Person constructor called");
        }

        @Override
        public String toString() {
            return "Person{name='" + name + "', age=" + age + "}";
        }
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, InstantiationException {
        // 使用反射获取 Unsafe 的私有字段 theUnsafe
        Field field = Unsafe.class.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        Unsafe unsafe = (Unsafe) field.get(null);

        System.out.println("Unsafe 实例获取成功：" + unsafe);

        long allocateMemory = unsafe.allocateMemory(1024L); // 创建一个1024字节
        System.out.println("allocateMemory的地址： " + allocateMemory);

        unsafe.putInt(allocateMemory,100);
        System.out.println("allocateMemory的地址： " + unsafe.getInt(allocateMemory));

        // 2️⃣ 修改对象私有字段的值
        Person person = new Person();


        // 获取字段的偏移地址
        long ageOffset = unsafe.objectFieldOffset(Person.class.getDeclaredField("age"));
        long nameOffset = unsafe.objectFieldOffset(Person.class.getDeclaredField("name"));

        System.out.println("\n📦 Original: " + person);

        // 修改字段的值（不需要 setter）
        unsafe.putInt(person, ageOffset, 25);
        unsafe.putObject(person, nameOffset, "Jerry");

        System.out.println("✏️ Modified: " + person);

        // 3️⃣ 分配堆外内存并写入数据
        System.out.println("\n💾 Allocating off-heap memory...");
        long size = 1024;
        long memoryAddress = unsafe.allocateMemory(size);
        unsafe.setMemory(memoryAddress, size, (byte) 0); // 清空内存

        // 写入一个整数到内存中
        int value = 123456789;
        unsafe.putInt(memoryAddress, value);

        // 读取出来验证
        int readValue = unsafe.getInt(memoryAddress);
        System.out.println("🧠 Read from off-heap memory: " + readValue);

        // 最后记得释放内存
        unsafe.freeMemory(memoryAddress);

        // 4️⃣ 不调用构造函数创建对象
        System.out.println("\n🧱 Creating object without calling constructor...");
        Person emptyPerson = (Person) unsafe.allocateInstance(Person.class);
        System.out.println("🆕 Uninitialized Person: " + emptyPerson);
    }
}
